package com.laobiao.file_netty_lib.packet.command.Mkdir;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import com.laobiao.file_netty_lib.content.FileContentApplication;
import com.laobiao.file_netty_lib.exception.FileBaseException;
import com.laobiao.file_netty_lib.packet.command.BaseCommandPacket;
import com.laobiao.file_netty_lib.packet.command.CommandCirculationType;
import com.laobiao.file_netty_lib.packet.command.PacketCommandType;
import com.laobiao.file_netty_lib.util.BinaryConvertUtil;

public class MkdirCommand extends BaseCommandPacket{
	
	private String remoteDirPath;
	
	public MkdirCommand() {
		super();
		setCommand(PacketCommandType.MKDIR);
		setBusinessGroup(FileContentApplication.getLastBusinessNumber());
	}
	
	public MkdirCommand(String remoteDirPath, Integer businessGroup) {
		super();
		setCommand(PacketCommandType.MKDIR);
		if (businessGroup != null) {
			setBusinessGroup(businessGroup);
		} else {
			setBusinessGroup(FileContentApplication.getLastBusinessNumber());
		}
		this.remoteDirPath = remoteDirPath;
	}
	
	public MkdirCommand(byte[] commandBytes) {
		ByteBuffer buf = setBaseCommand(commandBytes);

		/**
		 * 目录名长度
		 */
		byte[] chunk = new byte[4];
		buf.get(chunk);
		int remoteNameSize = BinaryConvertUtil.byteArrayToInt(chunk);// 文件名长度
		/**
		 * 目录
		 */
		chunk = new byte[remoteNameSize];
		buf.get(chunk);
		try {
			setRemoteDirPath(new String(chunk, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			throw new FileBaseException("接收到的命令中文件名编码失败！", FileBaseException.ERR_PARAM_WRONG);
		}
	}
	
	

	public String getRemoteDirPath() {
		return remoteDirPath;
	}

	public void setRemoteDirPath(String remoteDirPath) {
		this.remoteDirPath = remoteDirPath;
	}

	@Override
	protected byte[] getCommContentBytes() {
		ByteBuffer buf = ByteBuffer.allocate(1014);
		try {
			byte[] filePathBytes = remoteDirPath.getBytes("UTF-8");
			buf.put(BinaryConvertUtil.intToByteArray(filePathBytes.length));// 设置文件名
			buf.put(filePathBytes);// 设置文件名
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			throw new FileBaseException("文件名无法转换编码：" + remoteDirPath, e, FileBaseException.ERR_PARAM_WRONG);
		}
		return buf.array();
	}

	@Override
	public CommandCirculationType circulationType() {
		// TODO Auto-generated method stub
		return CommandCirculationType.BUSINESS;
	}

}
